package servlet;

import com.aliyun.oss.ServiceException;
import org.apache.commons.codec.binary.Base64;
import redis.clients.jedis.ShardedJedis;
import util.RSAUtil;
import util.RedisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.util.concurrent.TimeUnit;

@WebServlet(name = "productGetPublicKey", value = "/product/getPublicKey")
public class ProductRSAServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("username");
        System.out.println("username: " + userName);
        try {
            // 生成密钥对，其中的公钥私钥是唯一对应的
            KeyPair keyPair = RSAUtil.getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            System.out.println("公钥    " + publicKey);
            System.out.println("私钥    " + privateKey);
            // 将公钥私钥保存到本地文件
//            File file = new File("src/main/resources/template/publicKey_privateKey.txt");
//            FileWriter fileWriter = new FileWriter(file);
//            fileWriter.write("公钥    " + publicKey + "\n");
//            fileWriter.write("私钥    " + privateKey);
//            fileWriter.flush();
//            fileWriter.close();

            // 将公钥私钥保存到redis，有效期为5分钟
            ShardedJedis jedis = RedisUtil.getJedis();  //获取redis连接
            jedis.set(userName + "_privateKey", privateKey);
            jedis.set(userName + "_publicKey", publicKey);
             // 有效期为5分钟
            jedis.expire(userName + "_privateKey", 300);
            jedis.expire(userName + "_publicKey", 300);
            jedis.close();
            System.out.println(publicKey);
            System.out.println(privateKey);
            PrintWriter out = resp.getWriter();
            out.write(publicKey);
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println("获取公钥失败");
        }
    }
}
